package com.jzo2o.orders.manager.listener;

import com.alibaba.fastjson.JSON;
import com.jzo2o.api.trade.enums.TradingStateEnum;
import com.jzo2o.common.constants.MqConstants;
import com.jzo2o.common.expcetions.DBException;
import com.jzo2o.common.model.msg.TradeStatusMsg;
import com.jzo2o.common.utils.CollUtils;
import com.jzo2o.orders.base.enums.OrderPayStatusEnum;
import com.jzo2o.orders.base.enums.OrderStatusEnum;
import com.jzo2o.orders.base.model.dto.OrderUpdateStatusDTO;
import com.jzo2o.orders.base.service.IOrdersCommonService;
import com.jzo2o.orders.manager.service.IOrdersCreateService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
import org.springframework.transaction.support.TransactionTemplate;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 监听支付订单状态更新的消息
 * @author JIAN
 */
@Slf4j
@Component
public class TradeStatusListener {
    @Resource
    private IOrdersCreateService ordersCreateService;
    @Resource
    private IOrdersCommonService ordersCommonService;
    @Resource
    private TransactionTemplate transactionTemplate;


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS),
            exchange = @Exchange(name = MqConstants.Exchanges.TRADE, type = ExchangeTypes.TOPIC),
            key = MqConstants.RoutingKeys.TRADE_UPDATE_STATUS))
    public void onStatusUpdateMsg(String msg) {
        log.info("接收到支付结果状态的消息 ({}) -> {}", MqConstants.Queues.ORDERS_TRADE_UPDATE_STATUS, msg);

        List<TradeStatusMsg> msgList = JSON.parseArray(msg, TradeStatusMsg.class);
        if (CollUtils.isEmpty(msgList)) {
            return;
        }

        // 处理当前微服务并且支付成功的订单
        List<TradeStatusMsg> tradeStatusMsgList = msgList.stream()
                .filter(statusMsg -> ordersCreateService.PRODUCT_APP_ID.equals(statusMsg.getProductAppId())
                        && TradingStateEnum.YJS.getCode().equals(statusMsg.getStatusCode()))
                .collect(Collectors.toList());

        transactionTemplate.executeWithoutResult(status -> {
            for (TradeStatusMsg tradeStatusMsg : tradeStatusMsgList) {
                if (!ordersCommonService.updateStatus(OrderUpdateStatusDTO.builder()
                        .id(tradeStatusMsg.getProductOrderNo())
                        .originStatus(OrderStatusEnum.NO_PAY.getStatus())
                        .targetStatus(OrderStatusEnum.DISPATCHING.getStatus())
                        .payStatus(OrderPayStatusEnum.PAY_SUCCESS.getStatus())
                        .tradingOrderNo(tradeStatusMsg.getTradingOrderNo())
                        .transactionId(tradeStatusMsg.getTransactionId())
                        .tradingChannel(tradeStatusMsg.getTradingChannel())
                        .payTime(LocalDateTime.now()).build())) {
                    throw new DBException("更新订单状态失败");
                }
            }
        });
    }
}